package com.cjq.core.route;

import com.cjq.config.GatewayConfig;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
public class DynamicRouter {

    private final Map<String, RouteDefinition> routes = new ConcurrentHashMap<>();
    private final List<RouteDefinition> routeList;

    public DynamicRouter(GatewayConfig config) {
        this.routeList = config.getRouteList();
        // 从配置中心（如Nacos/Apollo）加载路由规则
        loadRoutesFromConfigCenter();
    }

    public RouteDefinition match(String path) {
        return routes.values().stream()
                .filter(route -> path.startsWith(route.getPrefix()))
                .findFirst()
                .orElse(null);
    }

    // 动态更新路由（可通过API触发）
    public void updateRoute(RouteDefinition route) {
        routes.put(route.getId(), route);
    }

    private void loadRoutesFromConfigCenter() {
        if (!routeList.isEmpty()){
            routeList.forEach(route->{
                routes.put(route.getId(),route) ;
            });
        }
    }
}